<?php
class TesseractOCR {

  static function recognize($originalImage) {
    $tifImage       = TesseractOCR::convertImageToTif($originalImage);
    $configFile     = TesseractOCR::generateConfigFile(func_get_args());
    $outputFile     = TesseractOCR::executeTesseract($tifImage, $configFile);
    $recognizedText = TesseractOCR::readOutputFile($outputFile);
    TesseractOCR::removeTempFiles(sys_get_temp_dir()."\\$tifImage", sys_get_temp_dir()."\\$outputFile", sys_get_temp_dir()."\\$configFile");
    return $recognizedText;
  }

  static function convertImageToTif($originalImage) {
    $tifImage = "tesseract-ocr-tif-".rand().".tiff";
    exec ("convert -colorspace gray +matte $originalImage ".sys_get_temp_dir()."\\$tifImage");
    //echo "-".system ("convert -colorspace gray +matte $originalImage ".sys_get_temp_dir()."\pruebaD.tiff")."-<br/>";
    //echo "-".passthru ("convert -colorspace gray +matte $originalImage ".sys_get_temp_dir()."\pruebaE.tiff")."-<br/>";
    //echo "-".shell_exec ("convert -colorspace gray +matte $originalImage ".sys_get_temp_dir()."\pruebaF.tiff")."-<br/>";
    return $tifImage;
  }

  static function generateConfigFile($arguments) {
    $configFile = "tesseract-ocr-config-".rand().".conf";
    exec("touch ".sys_get_temp_dir()."\\$configFile")."-<br/>";
    $whitelist = TesseractOCR::generateWhitelist($arguments);
    if(!empty($whitelist)) {
      $fp = fopen(sys_get_temp_dir()."\\$configFile", 'w');
      //echo $fp;
      fwrite($fp, "tessedit_char_whitelist $whitelist");
      fclose($fp);
    }
    return $configFile;
  }

  static function generateWhitelist($arguments) {
    array_shift($arguments); //first element is the image path
    $whitelist = '';
    foreach($arguments as $chars) $whitelist.= join('', (array)$chars);
    return $whitelist;
  }

  static function executeTesseract($tifImage, $configFile) {
    $outputFile = "tesseract-ocr-output-".rand();
    exec("tesseract ".sys_get_temp_dir()."\\$tifImage ".sys_get_temp_dir()."\\$outputFile nobatch ".sys_get_temp_dir()."\\$configFile");
    return $outputFile.'.txt'; //tesseract appends txt extension to output file
  }

  static function readOutputFile($outputFile) {
    //return ((file(sys_get_temp_dir()."\\$outputFile")));
    return trim(file_get_contents(sys_get_temp_dir()."\\$outputFile"));
  }

  static function removeTempFiles() { array_map("unlink", func_get_args()); }
}
?>
